package org.kev.transit.data;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;

import org.apache.commons.httpclient.HttpException;
import org.json.JSONException;
import org.kev.transit.TransitProvider;
import org.kev.transit.util.JsonHelper;
import org.kev.transit.util.WebHelper;
import org.kev.transit.worker.RouteUpdateWorker;

import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.provider.BaseColumns;
import android.util.Log;





/**
 * Route Data Object represents a row in the route table
 * @author kevin
 *
 */
public class Route implements BaseColumns{
	/**
	* The default sort order for this table
	*/
	public static final String DEFAULT_SORT_ORDER = "title DESC";
	public static final String ROUTE_TYPE = "route_type";
	public static final String TITLE = "title";
	public static final String CREATE_DATE = "create_date";
	public static final String TABLE_NAME = "route";
    public static final Uri CONTENT_URI = Uri.parse("content://"+TransitProvider.AUTH+"/"+TABLE_NAME);
	public static final String ROUTE_ID ="route_id";
	private static final String TAG = null;
    public String id=null;
    public String title=null;
    public long createDate=0;
	public String routeType=null;
    
	/**
	 * 
	 * @param parent calling activity
	 * @param routeTypeId
	 * @return list of data objects
	 */
    public static final ArrayList <Route> getData(Activity parent,String routeTypeId){
    	ArrayList <Route> list=new ArrayList <Route>();
    	Cursor cursor=null;
    	boolean hasData=false;
    	boolean hasExpiredData = false;
		try{			
				String where = Route.ROUTE_TYPE+"=? ";
				String args[]={routeTypeId};
				cursor = parent.managedQuery(Route.CONTENT_URI, 
						new String[] {Route.ROUTE_ID,Route.ROUTE_TYPE,Route.TITLE}, where, args, null);
				list = new ArrayList <Route>();
			
				while(cursor.next()){
					hasData=true;
					String id=cursor.getString(0);
					String rtype=cursor.getString(1);
					String name=cursor.getString(2);

					Route r =new Route();
					r.id=id;
					r.title=name;
					r.routeType=rtype;
					Log.d(TAG,r.toXml() );
					list.add(r);
				}
		}finally{
			if (cursor!=null)
				cursor.close();
		}
		if(!hasData || hasExpiredData){
			try {
				list =retrieveDataFromWeb(parent,routeTypeId);
			} catch (Exception e) {
				Log.e(TAG,"Unable to retrieve data from web!",e);
			} 
		}
		return list;
    }
    
	/**
	 * calls web service 
	 * Returning a list of data objects.  It will then try to call
	 * a background worker thread to cache the data in the local DB.
	 * @param parent calling reference
	 * @param rout type id
	 * @return list of Direction objects
	 * @throws HttpException
	 * @throws IOException
	 * @throws JSONException
	 */
	private static ArrayList <Route> retrieveDataFromWeb(Activity parent,String rType) throws HttpException, IOException, JSONException{
		Log.d(TAG,"did not find any data in tables get it from the web");
		String jsonText=null;
		jsonText=WebHelper.getRoute(rType);
		ArrayList <Route> list= new ArrayList <Route>();
		list= JsonHelper.getRoutes(jsonText);
		Log.d(TAG,"Retrieved data from web="+list.size());
		//update db in background
		RouteUpdateWorker worker = new RouteUpdateWorker(parent, list);
		Thread t = new Thread(worker);
		t.start();
		//worker.run();
		return list;
	}
    /**
     * 
     */
    @Override
    public String toString(){
    	return title;
    }
	/**
	 * dumps current instance values to a string 
	 * in a XML format
	 * @return XML
	 */
	public String toXml(){
		return
		"<"+TABLE_NAME+">\n"+
		"\t<"+Route._ID+">"+id+"</"+Route._ID+">\n"+
		"\t<"+Route.TITLE+">"+title+"<"+Route.TITLE+">\n"+
		"\t<"+Route.ROUTE_TYPE+">"+routeType+"</"+Route.ROUTE_TYPE+">\n"+
		"\t<"+Route.CREATE_DATE+">"+createDate+"</"+Route.CREATE_DATE+">\n"+
		"</"+TABLE_NAME+">\n" ;
	}
}
